#include <iostream>
#include<unistd.h>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

void ChildWrit(const int wfd)
{
    char buffer[1024];
    int cnt=0;
    while(true)
    {
        //snprintf是C语言的字符串处理函数，在需要读取的字符串末尾会自动添加/0，
        //而下面的read函数是系统级别的函数，所以在处理字符串的时候需要我们需要预留一个字节空间来添加/0
        snprintf(buffer,sizeof(buffer),"i am child,witing now,my pid:%d,cnt:%d",getpid(),cnt++);
        write(wfd,buffer,strlen(buffer));
        sleep(1);
    }

}
void FatherRead(const int rfd)
{
    char buffer[1024];

    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            cout<<"child say:"<<buffer<<endl;
        }
    }
}
int main() {
    //创建管道
    int fds[2]={0};
    int n=pipe(fds);
    if(n<0)
    {
        cout<<"pipe error"<<endl;
    }
    else
    {
        cout<<"fds[0]"<<fds[0]<<endl;
        cout<<"fds[1]"<<fds[1]<<endl;
    }
    //创建子进程
    //关闭读写端形成单向通信信道
    pid_t id=fork();
    if(id==0)
    {
        close(fds[0]);
        ChildWrit(fds[1]);

        exit(0);
    }

    close(fds[1]);
    FatherRead(fds[0]);
    waitpid(id,nullptr,0);







    cout<<"test pipe"<<endl;
    return 0;
}